import Encrypt from '@/common/encrypt.js'
import jsrsasign from 'jsrsasign'
import api from '@/common/api.js'
import WXBizDataCrypt from '@/common/WXBizDataCrypt.js'
// import request from '@/common/request.js'

// 获取token
function getToken() {
	let data = {
		nvc_platform: '1', //平台标识
		// nvc_wx_identifier: '',
		// nvc_phone: ''
	};
	let postUrl = '',
		platform = '';
	// 获取设备系统信息
	uni.getSystemInfo({
		success: function(res) {
			platform = res.platform;
			// console.log(res.platform);
			if (res.platform == 'ios') {
				postUrl = '/Common/GetTokenIos/'
				data = JSON.stringify(data)
			} else {
				postUrl = '/Common/GetToken/'
				data = Encrypt.PublicEntryption(data)
			}

		}
	});

	// 通过Promise  async await 实现同步请求
	return new Promise((resolve, reject) => {
		uni.request({
			url: api.BASE_URL + postUrl,
			data: {
				ciphertext: data
			},
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
			},
			success: (res) => {
				// debugger
				// console.log(res.data);
				resolve(res);
				let token = {}
				if (platform == 'ios') {
					token.token = res.data.data;
				} else {
					token.token = Encrypt.PublicDecode(res.data.data); //解密
				}

				token = Encrypt.PublicEntryption(token)
				// debugger
				uni.setStorageSync('TokenData', token);
			},
			fail: (err) => {
				reject('err')
			}
		});
	})
}

function jumpLogin() {
	uni.navigateTo({
		url: '/pages/login/login'
	});
}

function upgradePrompt() {
	uni.showModal({
		content: "升级为会员后，可查看详细信息\n客服电话：19912348016",
		confirmColor: '#338b39',
		confirmText: '拨打',
		success: function(res) {
			if (res.confirm) {
				uni.makePhoneCall({
					phoneNumber: '19912348016'
				});
			} else if (res.cancel) {

			}
		}
	});
}

/**
 * 字符串长度截取，超出部分用“...”
 *
 * @param    {String}  str     需要截取的字符串
 * @param    {Number}  len     需要截取的长度
 *
 */
//cutStr('我是示例'，'2')
//我是...
function cutStr(str, len) {
	len = len * 2
	if (str.length * 2 <= len) {
		return str
	} else {
		var temp,
			icount = 0,
			patrn = /[^\x00-\xff]/,
			strre = "";
		for (var i = 0; i < str.length; i++) {
			if (icount < len - 1) {
				temp = str.substr(i, 1);
				if (patrn.exec(temp) == null) {
					icount = icount + 1
				} else {
					icount = icount + 2
				}
				strre += temp
			} else {
				break;
			}
		}
		return strre + "..."
	}
}
/**
 * 通过新闻type id获取对应名称
 *
 * @param    {Number}  id     新闻type id
 *
 */
//getNewsTypeName(1)
//我是...
function getNewsTypeName(type) {
	let typeName;
	// 类型：1统计数据 2行业资讯  3会议动态  4热点  5公告  6 精选好文 7 企业新闻
	switch (type) {
		case 1:
			typeName = "统计数据";
			break;
		case 2:
			typeName = "行业资讯";
			break;
		case 3:
			typeName = "会议动态";
			break;
		case 4:
			typeName = "热点";
			break;
		case 5:
			typeName = "公告";
			break;
		case 6:
			typeName = "精选好文";
			break;
		case 7:
			typeName = "企业新闻";
			break;
	}
	return typeName
}

function getWxPhone(encryptedData, sessionKey, iv) {
	let appId = 'wx072c285f62ebc740'
	var pc = new WXBizDataCrypt(appId, sessionKey)
	var data = pc.decryptData(encryptedData, iv)
	// console.log('解密后 data: ', data)
	return data
}

function numFixedTwo(num) {
	num += '';
	num = num.replace(/[^0-9|\.]/g, ''); //清除字符串中的非数字非.字符  

	if (/^0+/) //清除字符串开头的0  
		num = num.replace(/^0+/, '');
	if (!/\./.test(num)) //为整数字符串在末尾添加.00  
		num += '.00';
	if (/^\./.test(num)) //字符以.开头时,在开头添加0  
		num = '0' + num;
	num += '00'; //在字符串末尾补零  
	num = num.match(/\d+\.\d{2}/)[0];
	return num
}

function changeProductToArr(data) {
	console.log('11')
	let dataStr = ''
	for (let i = 0; i < data.length; i++) {
		dataStr = dataStr + data[i][5] + '；'
	}
	return dataStr
}

/**
 * 获取select组件 数据默认索引
 *
 * @param    {Arr}  arr     select组件 数据
 * @param    {name}  arr     select组件 name
 *
 */
//getSelectArrIndex(arr,['河北省','唐山市','开平区'])
//[2,3,6]
function getArrIndex(arr, name) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i].label == name) {
			return i;
		}
	}
}

function getSelectArrIndex(arrData, arrDefault) {
	// console.log(arrData)
	// console.log(arrDefault)
	let pIndex, cIndex, aIndex //省市区索引
	pIndex = getArrIndex(arrData, arrDefault[0])
	cIndex = getArrIndex(arrData[pIndex].children, arrDefault[1])
	aIndex = getArrIndex(arrData[pIndex].children[cIndex].children, arrDefault[2])
	// console.log(pIndex)
	// console.log(cIndex)
	// console.log(aIndex)
	return [pIndex, cIndex, aIndex]
}



function insert(arrfirst, arrlast, index) { //将数组arrlast插入数组arrfirst中，index是想要插入的位bai置

	if (index < 0) {
		zhiindex = 0;
	} else if (index > arrfirst.length) {
		index = arrfirst.length;
	}
	var arr = [];
	for (var i = 0; i < index; i++) {
		arr.push(arrfirst[i]);
	}
	for (var i = 0; i < arrlast.length; i++) {
		arr.push(arrlast[i]);
	}
	for (var i = index; i < arrfirst.length; i++) {
		arr.push(arrfirst[i]);
	}
	return arr;

}

// 对象数组快速排序
//key 排序依据关键字
//desc不存在默认升序
//desc存在降序
function arrayObjSort(arr, key, desc) {
	key = key || 'id';
	desc = desc || null;
	if (arr.length == 0) return [];

	var left = new Array();
	var right = new Array();
	var pivot = arr[0][key]; //分割值
	var pivotObj = arr[0]; //存储值

	if (desc === null) { //升序
		for (var i = 1; i < arr.length; i++) {
			arr[i][key] < pivot ? left.push(arr[i]) : right.push(arr[i]);
		}
	} else { //降序
		for (var i = 1; i < arr.length; i++) {
			arr[i][key] > pivot ? left.push(arr[i]) : right.push(arr[i]);
		}
	}
	return arrayObjSort(left, key, desc).concat(pivotObj, arrayObjSort(right, key, desc));
}
/**
 * 字符串替换
 *
 * @param    {String}  str         字符串
 * @param    {String}  AFindText   要替换的字符
 * @param    {String}  ARepText    替换成什么
 * @author
 */
function strReplaceAll(str, AFindText, ARepText) {
	debugger
	var raRegExp = new RegExp(AFindText, "g");
	return str.replace(raRegExp, ARepText);
}

/**
 * 数组去重
 *
 * @param    {Array}  arr         数组
 */

function arrayRemoveDup(arr) {
	var result = [];
	for (var i = 0; i < arr.length; i++) {
		var temp = arr.slice(i + 1, arr.length)
		if (temp.indexOf(arr[i]) == -1) {
			result.push(arr[i]);
		} else {
			continue;
		}
	}
	return result;
}

// 正则验证
let validation = {
	validationType: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, //只能输入包含（中文，数字，英文）
	validationPassword: /^(\w){6,16}$/, //校验密码：只能输入6-16个字母、数字、下划线
	validationCode: /^[0-9]{6}$/ //校验验证码：只能输入6数字
}

/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
 */
function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

function formatTime(number, format) {
	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
	var returnArr = []
	var date = new Date(number)
	returnArr.push(date.getFullYear())
	returnArr.push(formatNumber(date.getMonth() + 1))
	returnArr.push(formatNumber(date.getDate()))

	returnArr.push(formatNumber(date.getHours()))
	returnArr.push(formatNumber(date.getMinutes()))
	returnArr.push(formatNumber(date.getSeconds()))

	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i])
	}
	return format
}

function addAll(data) {
	let addAllMIddle = {
			children: [{
				label: '全部',
				value: ''
			}],
			label: '全部',
			value: ''
		},
		addAllSmall = {
			label: '全部',
			value: ''
		},
		addAllBig = {
			children: [{
				children: [{
					label: '全部',
					value: ''
				}],
				label: '全部',
				value: ''
			}],
			label: '全部',
			value: ''
		}
	// 添加二三级 "全部"
	data.forEach(item => {
		item.children.forEach(smallItem => {
			smallItem.children.unshift(addAllSmall)
		})
		item.children.unshift(addAllMIddle)
	});
	// 添加一级"全部"
	data.unshift(addAllBig)
	return data
}

module.exports = {
	getToken: getToken,
	jumpLogin: jumpLogin,
	cutStr: cutStr,
	getNewsTypeName: getNewsTypeName,
	getWxPhone: getWxPhone,
	numFixedTwo: numFixedTwo,
	changeProductToArr: changeProductToArr,
	getArrIndex: getArrIndex,
	getSelectArrIndex: getSelectArrIndex,
	getArrIndex: getArrIndex,
	getSelectArrIndex: getSelectArrIndex,
	insert: insert,
	upgradePrompt: upgradePrompt,
	arrayObjSort: arrayObjSort,
	strReplaceAll: strReplaceAll,
	arrayRemoveDup: arrayRemoveDup,
	validation: validation,
	formatTime: formatTime,
	addAll:addAll
}
